"""
投资组合页面渲染模块。
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px

# 从 app_setup 导入 logger (如果需要)
try:
    from .app_setup import logger
except ImportError:
    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

def get_real_trades():
    """从数据源获取真实交易记录"""
    try:
        return st.session_state.get('trade_history', [])
    except Exception as e:
        logger.error(f"获取交易历史失败: {e}")
        return []

def get_holdings_data():
    """从数据源获取真实持仓数据"""
    try:
        return st.session_state.get('holdings_data', [])
    except Exception as e:
        logger.error(f"获取持仓数据失败: {e}")
        return []

def render_portfolio():
    """渲染投资组合界面"""
    st.markdown('<div class="main-header">投资组合</div>', unsafe_allow_html=True)
    
    # 获取持仓数据
    holdings_df = pd.DataFrame(get_holdings_data())
    
    if not holdings_df.empty:
        render_portfolio_overview(holdings_df)
        render_holdings_distribution(holdings_df)
    else:
        st.warning("无有效持仓数据")
    
    render_trade_history()

def render_portfolio_overview(holdings_df):
    """基于真实数据渲染概览"""
    st.markdown('<div class="sub-header">组合概览</div>', unsafe_allow_html=True)
    
    total_value = holdings_df['市值'].sum()
    today_return = holdings_df['当日收益'].sum()
    total_return = holdings_df['累计收益'].sum()
    
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("组合总值", f"{total_value:,.2f}元")
    with col2:
        st.metric("当日收益", f"{today_return:,.2f}元")
    with col3:
        st.metric("累计收益", f"{total_return:,.2f}元")

def render_holdings_distribution(holdings_df):
    """渲染持仓分布"""
    st.markdown('<div class="sub-header">持仓分布</div>', unsafe_allow_html=True)
    
    # 行业分布
    fig = px.pie(holdings_df, names='行业', values='市值', title='行业分布')
    st.plotly_chart(fig, use_container_width=True)

def render_trade_history():
    """渲染交易历史"""
    st.markdown('<div class="sub-header">交易历史</div>', unsafe_allow_html=True)
    
    trades = get_real_trades()
    if trades:
        st.dataframe(pd.DataFrame(trades))
    else:
        st.warning("无交易历史数据")
